package com.example.pclimb.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.pclimb.model.User;
import com.example.pclimb.repository.UserRepository;

import java.util.List;

/**
 * 用户视图模型，负责处理用户相关的UI数据
 */
public class UserViewModel extends AndroidViewModel {
    private UserRepository repository;
    private LiveData<List<User>> allApprovedGuides;
    private LiveData<List<User>> pendingGuideApplications;
    private MutableLiveData<User> currentUser = new MutableLiveData<>();

    public UserViewModel(@NonNull Application application) {
        super(application);
        repository = new UserRepository(application);
        allApprovedGuides = repository.getAllApprovedGuides();
        pendingGuideApplications = repository.getPendingGuideApplications();
    }

    public void insert(User user, UserRepository.Callback<Long> callback) {
        repository.insert(user, callback);
    }

    public void update(User user) {
        repository.update(user);
    }

    public void delete(User user) {
        repository.delete(user);
    }

    public LiveData<User> login(String username, String password) {
        return repository.login(username, password);
    }

    public LiveData<List<User>> getAllApprovedGuides() {
        return allApprovedGuides;
    }

    public LiveData<List<User>> getPendingGuideApplications() {
        return pendingGuideApplications;
    }

    public LiveData<User> getUserById(int userId) {
        return repository.getUserById(userId);
    }

    public LiveData<User> getUserByUsername(String username) {
        return repository.getUserByUsername(username);
    }

    public void approveGuideApplication(int userId) {
        repository.approveGuideApplication(userId);
    }

    public void rejectGuideApplication(int userId) {
        repository.rejectGuideApplication(userId);
    }

    public void updateRating(int userId, float newRating) {
        repository.updateRating(userId, newRating);
    }

    /**
     * 更新用户信息
     * @param user 要更新的用户对象
     */
    public void updateUser(User user) {
        repository.update(user);
    }

    public void setCurrentUser(User user) {
        currentUser.setValue(user);
    }

    public LiveData<User> getCurrentUser() {
        return currentUser;
    }

    // 申请成为陪爬人员
    public void applyToBeGuide(User user, String certificationUrl) {
        user.setGuideApplied(true);
        user.setCertificationUrl(certificationUrl);
        user.setGuideApplication(User.APPLICATION_PENDING);
        repository.update(user);
    }

    /**
     * 根据申请状态获取用户
     */
    public LiveData<List<User>> getUsersByApplicationStatus(int applicationStatus) {
        return repository.getUsersByApplicationStatus(applicationStatus);
    }
} 